package com.ruoyi.orders.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.medication.domain.Medication;
import com.ruoyi.medication.domain.MedicationStock;
import com.ruoyi.medication.mapper.MedicationMapper;
import com.ruoyi.orders.domain.OrderDetail;
import com.ruoyi.orders.domain.Orders;
import com.ruoyi.orders.mapper.OrdersMapper;
import com.ruoyi.orders.service.IOrdersService;
import com.ruoyi.prescription.domain.Prescription;
import com.ruoyi.product.domain.SupplierProduct;
import com.ruoyi.product.mapper.SupplierProductMapper;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 药品采购订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-12
 */
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private MedicationMapper medicationMapper;

    @Autowired
    private SupplierProductMapper supplierProductMapper;

    /**
     * 查询药品采购订单
     * 
     * @param id 药品采购订单主键
     * @return 药品采购订单
     */
    @Override
    public Orders selectOrdersById(Long id) {
        return ordersMapper.selectOrdersById(id);
    }

    /**
     * 查询药品采购订单列表
     * 
     * @param orders 药品采购订单
     * @return 药品采购订单
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * 新增药品采购订单
     * 
     * @param orders 药品采购订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertOrders(Orders orders) {

        // Orders or = new Orders();
        // or.setOrderTime(orders.getOrderTime());
        // or.setAmount(orders.getAmount());
        // or.setCreateTime(DateUtils.getNowDate());
        // or.setStatus(orders.getStatus());
        // int rows = ordersMapper.insertOrders(orders);
        //
        // List<OrderDetail> orderDetailList = orders.getOrderDetailList();
        // Long id = or.getId();
        // if (StringUtils.isNotNull(orderDetailList))
        // {
        // List<OrderDetail> list = new ArrayList<OrderDetail>();
        // for (OrderDetail orderDetail : orderDetailList)
        // {
        // orderDetail.setOrderId(id);
        // list.add(orderDetail);
        // }
        // if (list.size() > 0)
        // {
        // ordersMapper.batchOrderDetail(list);
        // }
        // }

        orders.setCreateTime(DateUtils.getNowDate());
        orders.setOrderTime(DateUtils.getNowDate());
        orders.setStatus("1");
        int rows = ordersMapper.insertOrders(orders);
        insertOrderDetail(orders);
        return rows;
    }

    /**
     * 修改药品采购订单
     * 
     * @param orders 药品采购订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOrders(Orders orders) {
        if (orders.getOrderDetailList() != null)
        {
            ordersMapper.deleteOrderDetailByOrderId(orders.getId());
            insertOrderDetail(orders);
        }
        if (orders.getStatus().equals("2")) {
            insertMedicatioinStocak(orders);
        }
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除药品采购订单
     * 
     * @param ids 需要删除的药品采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrdersByIds(Long[] ids) {
        ordersMapper.deleteOrderDetailByOrderIds(ids);
        return ordersMapper.deleteOrdersByIds(ids);
    }

    /**
     * 删除药品采购订单信息
     * 
     * @param id 药品采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrdersById(Long id) {
        ordersMapper.deleteOrderDetailByOrderId(id);
        return ordersMapper.deleteOrdersById(id);
    }

    /**
     * 新增采购订单明细信息
     * 
     * @param orders 药品采购订单对象
     */
    public void insertOrderDetail(Orders orders) {
        List<OrderDetail> orderDetailList = orders.getOrderDetailList();
        Long id = orders.getId();
        if (StringUtils.isNotNull(orderDetailList)) {
            List<OrderDetail> list = new ArrayList<OrderDetail>();
            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setOrderId(id);
                list.add(orderDetail);
            }
            if (list.size() > 0) {
                ordersMapper.batchOrderDetail(list);
            }
        }
    }

    /**
     * 新增药物库存
     *
     * @param orders 药品采购订单对象
     */
    public void insertMedicatioinStocak(Orders orders) {

        Long id = orders.getId();
        Orders order = ordersMapper.selectOrdersById(id);
        List<OrderDetail> orderDetailList = ordersMapper.selectOrderDetailList(order.getId());
        if (orderDetailList.size() > 0) {
            List<MedicationStock> list = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                Medication medication = medicationMapper.selectMedicationById(orderDetail.getMedicationId());
                SupplierProduct supplierProduct = new SupplierProduct();
                supplierProduct.setProductCode(medication.getNumber());
                supplierProduct.setSupplierId(orderDetail.getSupplierId());
                List<SupplierProduct> productList = supplierProductMapper.selectSupplierProductList(supplierProduct);
                SupplierProduct product = productList.get(0);
                MedicationStock stock = new MedicationStock();
                stock.setMedicationId(medication.getId());
                stock.setSupplierId(orderDetail.getSupplierId());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateUtils.getNowDate());
                stock.setCreateDate(calendar.getTime());
                calendar.add(Calendar.MONTH, product.getExpirationDate());
                stock.setExpirationDate(calendar.getTime());
                stock.setQuantity(orderDetail.getQuantity());
                stock.setPrice(orderDetail.getPrice());

                medication.setStock(medication.getStock() + orderDetail.getQuantity());
                medicationMapper.updateMedication(medication);
                list.add(stock);
            }
            medicationMapper.batchMedicationStock(list);
        }
    }

    /**
     * 自动审核采购订单
     * 每1分钟检查一次，将创建时间超过5分钟的"申请中"采购订单自动设置为"已完成"
     */
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void autoCheckPrescription() {
        // 查询所有状态为"申请中"的采购订单
        Orders query = new Orders();
        query.setStatus("1"); // 1 表示申请中
        List<Orders> orders = ordersMapper.selectOrdersList(query);

        // 获取当前时间
        Date now = new Date();

        // 遍历采购订单列表
        for (Orders order : orders) {
            // 计算采购订单创建时间到现在的分钟数
            long minutes = TimeUnit.MILLISECONDS.toMinutes(
                    now.getTime() - order.getCreateTime().getTime());

            // 如果超过5分钟，自动设置为已完成
            if (minutes >= 5) {
                order.setStatus("2"); // 2 表示已完成
                updateOrders(order);
            }
        }
    }
}
